const { Controller } = require('varal');

const { listToTree } = require('../helpers/function');

const xlsx = require('node-xlsx');
const fs = require('fs');
const path = require('path');
const dayjs = require('dayjs');

const { sequelize, UserPromoter } = require('../models');
const { Op } = require('sequelize');

class UserController extends Controller {
	constructor(app) {
		super(app);
	}

	async login({ fields }) {
		const serv = this.app.service('UserService');

		const { username, password } = fields;
		return serv.login(username, password).then((data) => {
			this.app.json({
				err_code: 0,
				data
			})
		}).catch((err) => {
			this.app.json({
				err_code: 1,
				err_msg: err.toString()
			});
		});
	}

	async profile(app) {
		const { id } = app.auth;

		const serv = this.app.service('UserService');
		const data = await serv.info({ id }).then((data) => data ? data.dataValues : {});
		if (!data?.id) return this.app.json({
			err_code: 1
		});

		const confServ = this.app.service('ConfigService');
		data.config = await confServ.info();

		//获取用户的模块权限
		const moduleServ = this.app.service('ModuleService');

		if (!data.role_id) {
			data.modules = [];
		} else {
			data.modules = listToTree(await moduleServ.get({
				status: 1,
				include_id: data.role?.auth && data.role.auth.length ? data.role?.auth.map((d) => d.key)?.flat().join(',') : 0
			}), 0);
		}

		this.app.json({
			err_code: 0,
			data
		})
	}

	async password(app) {
		const { original, latest } = app.fields;

		const serv = this.app.service('UserService');

		return serv.password(app.auth.id, original, latest).then(() => {
			this.app.json({
				err_code: 0
			})
		}).catch((err) => {
			this.app.json({
				err_code: 1,
				err_msg: err
			})
		})
	}

	async index() {
		const { fullname, phone, status, username, gender, page = 1, role_id, tree_parent_fullname, team_parent_fullname, create_time, submit } = this.app.fields;
		let { page_size = 20 } = this.app.fields;

		if (submit === 'export') page_size = 1 / 0;
		/*
		const UserService = require('../services/UserService');
		const serv = new UserService(this.app);
		*/
		const serv = this.app.service('UserService');

		return serv.get({
			fullname, phone, status, username, gender, role_id, tree_parent_fullname, team_parent_fullname, create_time
		}, page, page_size).then(({ data, total }) => {
			if (submit === 'export') {
				//导出excel
				const excel = [{
					name: 'sheet1',
					data: [
						['序号', '用户名', '姓名', '性别', '手机号', '昵称', '角色', '推荐人', '销售团队', '用户标签', '状态', '注册时间']
					]
				}];
				data.forEach((d) => {
					excel[0].data.push([
						d.id,
						d.username,
						d.fullname,
						d.gender === 1 ? '男' : '女',
						d.phone,
						d.nickname,
						d?.role?.name,
						d?.tree_parent?.fullname || d?.tree_parent?.phone,
						d?.team_parent?.fullname || d?.team_parent?.phone,
						d.label || '',
						d.status === 1 ? '正常' : '冻结',
						d.create_time
					]);
				})

				const buffer = xlsx.build(excel);
				const filePath = path.join(__dirname, `../public/xlsx/${dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
				fs.writeFileSync(filePath, buffer);

				return this.app.json({
					err_code: 0,
					data: {
						url: `https://mp.kachewo.com/${filePath.replace(path.join(__dirname, '../public/'), '')}`
					}
				});
			} else {
				this.app.json({
					err_code: 0,
					data: {
						data,
						total
					}
				})
			}
		});
	}

	async info() {
		const { id } = this.app.fields;
		const serv = this.app.service('UserService');
		const data = await serv.info({ id });

		this.app.json({
			data
		})
	}

	async delete() {
		const { id } = this.app.fields;

		const serv = this.app.service('UserService');

		return serv.delete(id).then(() => {
			this.app.json({
				err_code: 0
			})
		})
	}

	async save() {
		const params = this.app.fields;

		const serv = this.app.service('UserService');

		return serv.save(params).then(() => {
			this.app.json({
				err_code: 0
			})
		}).catch((err) => {
			this.app.json({
				err_code: 1,
				err_msg: err.toString()
			})
		});

	}

	async import() {
		const { files, fields } = this.app;
		const { department_id } = fields;

		//导入文件
		const { path: file } = files[0];

		//Parse a buffer | file
		const data = xlsx.parse(file, {
			//转换日期格式
			cellDates: true
		});

		const serv = this.app.service('UserService');
		return serv.import(data, { department_id }).then(() => {
			return this.app.json({
				err_code: 0
			})
		})
	}

	async promoter() {
		const { fullname, phone, page = 1, page_size = 20, create_time } = this.app.fields;
		const where = {};
		if (fullname) where['fullname'] = { [Op.like]: `%${fullname}%` };
		if (phone) where['phone'] = { [Op.like]: `%${phone}%` };

		where[Op.and] = [];
		if (create_time?.length) {
			where[Op.and].push(sequelize.where(sequelize.fn('date_format', sequelize.col('UserPromoter.create_time'), '%Y-%m-%d'), {
				[Op.between]: create_time
			}));
		}

		const { count: total, rows: data } = await UserPromoter.findAndCountAll({
			include: ['user'],
			where,
			offset: (page - 1) * page_size,
			limit: page_size * 1,
			order: [
				['id', 'desc']
			]
		});

		this.app.json({
			err_code: 0,
			data: {
				data,
				total
			}
		});
	}

	async deletePromoter() {
		const { id } = this.app.fields;
		await UserPromoter.destroy({
			where: {
				id: { [Op.in]: String(id).split(',') }
			}
		});
		this.app.json({
			err_code: 0
		})
	}
}

exports = module.exports = UserController;
